package com.wwdx.service.impl;

import com.google.common.collect.Maps;
import com.wwdx.model.WwdxCouponLogModel;
import com.wwdx.service.WwdxCouponLogServiceI;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author liguoliang
 * @date 2018/4/24 22:48
 */
@Service
public class WwdxCouponLogServiceImpl extends BaseServiceImpl<WwdxCouponLogModel> implements WwdxCouponLogServiceI{

    @Override
    public Long selectModelCount(WwdxCouponLogModel model) {
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(4);
        String hql = "select count(1) from WwdxCouponLogModel\t"+getParams(model,params);
        return count(hql,params);
    }

    private String getParams(WwdxCouponLogModel model, Map<String, Object> params){
        StringBuilder sb = new StringBuilder("where 1=1\n");
        String date = model.getDate();
        String dateEnd = model.getDateEnd();
        if (StringUtils.isNotBlank(date) && StringUtils.isNotBlank(dateEnd)){
            sb.append("and gmtCreated BETWEEN :date AND :dateEnd\n");
            params.put("date",new LocalDate(date).toDate());
            params.put("dateEnd",new LocalDate(dateEnd).toDate());
        }
        return sb.toString();
    }

    @Override
    public List<WwdxCouponLogModel> selectModelList(WwdxCouponLogModel model, Integer page, Integer rows) {
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(4);
        String hql = "from WwdxCouponLogModel\t"+getParams(model,params)+"\torder by gmtCreated desc";
        return this.execute(find(hql, params, page, rows));
    }

    private List<WwdxCouponLogModel> execute(List<WwdxCouponLogModel> couponLogModels){
        couponLogModels.forEach(model-> model.setUserName(wwdxPersonalService.getByUnionid(model.getUnionid()).getNickname()));
        return couponLogModels;
    }

    @Override
    public List<WwdxCouponLogModel> list(String unionId,Integer status) {
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(2);
        params.put("unionid",unionId);
        String hql = "from WwdxCouponLogModel where unionid=:unionid and DATEDIFF(gmtCreated,CURDATE())>=0\t";
        if (status != null){
            params.put("status",status);
            hql += "and status=:status";
        }
        return this.find(hql, params);
    }
}